package com.kischang.blog.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class RandomJpeg {
	private int WIDTH = 150;
	private int HEIGHT = 40;
	private StringBuilder code = new StringBuilder();
	private BufferedImage image ;
	private Graphics g;
	
	public RandomJpeg(){
		image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
	}
	
	public String getCodeStr(){
		return code.toString();
	}
	
	public BufferedImage getNewDefaultImage(){
		g = image.getGraphics();
		setBackground(g, Color.WHITE);
		setBorder(g,Color.DARK_GRAY);
		setRandomLine(g, 5,Color.GREEN);
		drawRandomData((Graphics2D)g, Color.RED);
		return image;
	}
	
	private void setBackground(Graphics g,Color color) {
		g.setColor(color);
		g.fillRect(0, 0, WIDTH, HEIGHT);
	}

	private void setBorder(Graphics g,Color color) {
		g.setColor(color);
		g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
	}
	
	private void setRandomLine(Graphics g,int disturbNum,Color color) {
		g.setColor(color);
		for(int i=0 ; i<disturbNum ; i++){
			int x1 = new Random().nextInt(WIDTH);
			int y1 = new Random().nextInt(HEIGHT); 
			int x2 = new Random().nextInt(WIDTH);
			int y2 = new Random().nextInt(HEIGHT); 
			g.drawLine(x1, y1, x2, y2);
		}
	}
	
	private void drawRandomData(Graphics2D g,Color color) {
		
		g.setColor(color);
		
		GraphicsEnvironment eq = GraphicsEnvironment.getLocalGraphicsEnvironment();
		String[] fontNames = eq.getAvailableFontFamilyNames();
		
		g.setFont(new Font(fontNames[0], Font.BOLD, 25));
		
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
		int x = 5;   
		for(int i=0;i<4;i++){
			int degree = new Random().nextInt()%30;   //-30 ->30
			String c = base.charAt(new Random().nextInt(base.length())) + ""; 
			code.append(c);
			g.rotate(degree*Math.PI/180 , x , 20);
			g.drawString(c, x+10, 25);
			g.rotate(-degree*Math.PI/180 , x , 20);
			x += 30;
		}
	}
}
